// components/search/index.js
import {
  KeywordModel
} from '../../models/keyword'
import {
  paginationBev
} from '../behaviors/pagination'

const keywordModel = new KeywordModel()

Component({
  behaviors: [paginationBev],

  /**
   * 组件的属性列表
   */
  properties: {
    more: {
      type: Number,
      observer: 'loadMore',
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    searching: false,
    q: '',
    loadingCenter: false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onCancel(event) {
      this.initialize()
      this.triggerEvent('cancel', {}, {})
    },

    onConfirm(event) {
      this.showResult()
      this.showLoadingCenter()
      // this.initialize()

      const word = event.detail.value || event.detail.text
      keywordModel.search(0, word).then((res) => {
        this.setMoreData(res.books)
        this.setTotal(res.total)
        this.setData({
          q: word,
        })
        keywordModel.addToHistory(word)
        this.closeLoadingCenter()
      })
    },

    onDelete(event) {
      this.initialize()
      this.closeResult()
    },

    loadMore() {
      if (!this.data.q) return

      if (this.isLocked()) {
        return
      }

      if (this.hasMore()) {
        this.lock()
        const start = this.getCurrentStart()
        keywordModel.search(start, this.data.q)
          .then((res) => {
            this.setMoreData(res.books)
            this.unlock()
          }, (err) => {
            this.unlock()
          })
      }
    },

    showResult() {
      this.setData({
        searching: true,
      })
    },

    closeResult() {
      this.setData({
        searching: false,
        q:'',
      })
    },


    showLoadingCenter() {
      this.setData({
        loadingCenter: true,
      })
    },

    closeLoadingCenter() {
      this.setData({
        loadingCenter: false,
      })
    },
  },

  attached() {
    const historyWords = keywordModel.getHistory()

    this.setData({
      historyWords: historyWords,
    })

    keywordModel.getHot().then((res) => {
      this.setData({
        hotWords: res.hot,
      })
    })
  },
})
